package com.yimaxiaoerlang.module_signalling.core;

import android.util.Log;

import com.yimaxiaoerlang.module_signalling.YMRTMChannel;
import com.yimaxiaoerlang.module_signalling.YMRTMClient;
import com.yimaxiaoerlang.module_signalling.model.YMRTMMessage;
import com.yimaxiaoerlang.module_signalling.utils.MessageUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class YMRTMClientImpl extends YMRTMClient implements YMKEvent {

    private final String TAG = "ZtmClient";

    private String appKey;
    private String appSecret;
    private YMRtmClientListener clientListener;

    private boolean verifySuccessful = true;
    private YMRTMLoginCallback loginCallback;
    private YMSocketManager mClient = new YMSocketManager();
    private YMRTMChannel nowChannel;
    private String mUserId = "";

    public YMRTMClientImpl(String appKey, String appSecret, YMRtmClientListener clientListener) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.clientListener = clientListener;

        mClient.setkEvent(this);
    }

    @Override
    public void setSocketAddress(String address) {
        if (address == null) address = "wss://im.yimaxiaoerlang.cn/signal";
        mClient.setSOCKET_URL(address);
    }

    @Override
    public void release() {

    }

    @Override
    public void loginWithToken(String token, String userId, YMRTMLoginCallback resultCallback) {
        if (!verifySuccessful) {
            Log.e(TAG, "appid 校验失败");
            resultCallback.completion(YMRTMLoginStatusCode.RTMLoginErrorInvalidAppKeyOrAppSecret);
            return;
        }
        if (token == null || token.isEmpty()) {
            resultCallback.completion(YMRTMLoginStatusCode.RTMLoginErrorInvalidToken);
            return;
        }
        mUserId = userId;
        loginCallback = resultCallback;
        if (clientListener != null) {
            clientListener.onConnectionStateChanged(YMConnectionState.CONNECTION_STATE_CONNECTING);

        }
        mClient.connect(token);
    }

    @Override
    public void logoutWithCompletion() {
        mClient.unConnect();
    }

    @Override
    public YMRTMChannel createChannelById(String channelId) {
        nowChannel = new YMRTMChannel(mClient, channelId, mUserId, new YMRTMChannelLeaveListener() {

            @Override
            public void onLeave() {
                nowChannel = null;
            }
        });
        return nowChannel;
    }

    @Override
    public void sendMessage(String peerId, String message, YMRTMSendPeerMessageCallback callback) {
        String msg = MessageUtils.createPeerMessage(mUserId, peerId, message);
        mClient.sendMessage(msg);
        if (callback != null) {
            callback.completion(YMRTMSendPeerMessageStatusCode.RTMSendPeerMessageSuccess);
        }
    }

    @Override
    public void sendMessage(String peerId, String message) {
        String msg = MessageUtils.createPeerMessage(mUserId, peerId, message);
        mClient.sendMessage(msg);
    }

    @Override
    public void onConnect() {
        if (loginCallback != null) {
            loginCallback.completion(YMRTMLoginStatusCode.RTMLoginSuccess);
        }
        if (clientListener != null) {
            clientListener.onConnectionStateChanged(YMConnectionState.CONNECTION_STATE_CONNECTED);
        }
    }

    @Override
    public void onDisconnect() {
        if (clientListener != null) {
            clientListener.onConnectionStateChanged(
                    YMConnectionState.CONNECTION_STATE_DISCONNECTED
            );
        }
    }

    @Override
    public void reConnect() {
        if (clientListener != null) {
            clientListener.onConnectionStateChanged(
                    YMConnectionState.CONNECTION_STATE_RECONNECTING
            );
        }
    }

    @Override
    public void onMessage(String msg) {
        handleMessage(msg);
    }


    private void handleMessage(String msg) {
        YMRTMMessage message = getSocketMessage(msg);
        switch (message.getMsgType()) {
            case YMMessageType.RTMMessageTypeKickOff://其他设备登录
                //断开连接
                mClient.unConnect();
                //回调通知
                if (clientListener != null)
                clientListener.onConnectionStateChanged(YMConnectionState.CONNECTION_STATE_ABORTED);
                break;
            case YMMessageType.RTMMessageTypeServerDisConnected://服务端断开链接
                //重联
                mClient.reConnect();
                //回调通知
                if (clientListener != null)
                clientListener.onConnectionStateChanged(YMConnectionState.CONNECTION_STATE_RECONNECTING);
                break;
            default://消息
                if (nowChannel != null && nowChannel.getChannelId() != null && message.getChannelId() != null && nowChannel.getChannelId().equals(message.getChannelId())) {//频道拦截 房间消息拦截
                    nowChannel.onMessage(message);
                    return;
                }
                if (message.getMsgType() == YMMessageType.RTMMessageTypeChannelMembers) {//房间内的信令 人数变化
                    return;
                }
                if (message.getUid().equals(mUserId)) return;
                if (clientListener != null)
                clientListener.onMessageReceived(message.getData(), message.getUid());
                break;
        }
    }


    private YMRTMMessage getSocketMessage(String msg) {
        JSONObject jsonObject = null;
        YMRTMMessage message = new YMRTMMessage();
        try {
            jsonObject = new JSONObject(msg);
            message.setChannelId(jsonObject.optString("channelId"));
            message.setUid(jsonObject.optString("uid"));
            message.setTid(jsonObject.optString("tid"));
            message.setMsgType(jsonObject.optInt("msgType"));
            message.setErrorMsg(jsonObject.optString("errorMsg"));
            message.setData(jsonObject.optString("data"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return message;
    }
}
